package com.qf.listener;

import com.baomidou.mybatisplus.plugins.Page;
import com.qf.entity.Goods;
import com.rabbitmq.client.Channel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ItemQueueListener {

    @Autowired
    private Configuration configuration;

    @RabbitListener(queues = "${item.itemQueueName}")
    public void createItem(Goods goods, Channel channel, Message message) throws TemplateException, FileNotFoundException {

        File file = ResourceUtils.getFile("shop-16-item/src/main/resources/static");

        String staticPath = file.getAbsolutePath();

        // 1.准备数据
        Map<String, Object> map = new HashMap<>();
        map.put("goods", goods);
        map.put("gpngList", goods.getGpng().split("\\|"));

        FileWriter out = null;
        try {
            // 2.找到模板
            Template template = configuration.getTemplate("goodsItem.ftl");

            // 虽然我们项目里面写的全局的异常，但是在这里是资源相关的依赖需要捕获主
            out = new FileWriter(staticPath + File.separator + goods.getId() + ".html");
            template.process(map, out);

        } catch (IOException e) {
            log.error("生成item页面出现异常", e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
